package com.heima.test17;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

class SaveFile implements Runnable {

    private Socket accept;

    public SaveFile(Socket accept) {
        this.accept = accept;
    }

    @Override
    public void run() {
        try {
            UUID uuid = UUID.randomUUID();
            String fileName = uuid.toString().replace("-", "");

            //创建文件输出流 用来保存客户端传来的文件
            FileOutputStream fos = new FileOutputStream("pics/" + fileName);

            //3 获取输入流 用来接收图片数据
            InputStream is = accept.getInputStream();
            byte[] bytes = new byte[1024];
            int len;
            System.out.println("开始接收图片数据");
            while ((len = is.read(bytes)) != -1) {
                //保存客户端传来的文件
                fos.write(bytes, 0, len);
            }
            System.out.println("接收图片数据完毕");
            is.close();
            fos.close();
            accept.close();
            System.out.println(accept.getRemoteSocketAddress() + "的连接断开");
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}


public class FileUploadServer {
    public static void main(String[] args) throws IOException {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(10, 10, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

        //1 创建服务器的socket对象
        ServerSocket ss = new ServerSocket(20000);
        while (true) {
            //2 接收连接
            Socket accept = ss.accept();
            System.out.println("接收到来自" + accept.getRemoteSocketAddress() + "的连接");
            // new Thread(new SaveFile(accept)).start();
            pool.execute(new SaveFile(accept));
        }
    }
}
